<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="基础设置（数组字段）"
      width="700px"
      v-bind="$attrs"
      @open="onOpen"
      @close="onClose"
    >
      <el-form
        ref="elForm"
        :model="formData"
        size="small"
        label-width="100px"
      >
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="最小元素个数" prop="minItems">
              <el-input-number
                v-model="formData.minItems"
                placeholder="请输入"
                :min="0"
                :step="1"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大元素个数" prop="maxItems">
              <el-input-number
                v-model="formData.maxItems"
                placeholder="请输入"
                :step="1"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { reactive, getCurrentInstance, toRefs } from 'vue'

export default {
  name: 'ArrayDialog',
  inheritAttrs: false,
  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props, { emit }) {
    const state = reactive({
      dialogVisible: false,
      formData: {
        minItems: undefined,
        maxItems: undefined,
      },
    });

    const onOpen = () => {
      const { minItems, maxItems } = props.initData
      state.formData = { 
        ...state.formData,
        minItems,
        maxItems,
      };
      state.dialogVisible = true;
    }
    const { proxy } = getCurrentInstance();
    const onClose = () => {
      proxy.$refs.elForm.resetFields();
      state.dialogVisible = false;
    }
    const handleConfirm = () => {
      proxy.$refs.elForm.validate((valid) => {
        if (!valid) return;
        const newData = state.formData;
        proxy.mittBus.emit(`schema-update-${props.initData.editorId}`, {
          eventType: 'save-setting',
          // 之前的参数
          ...props.initData,
          // 设置数据
          newData,
        })
        onClose();
      })
    }

    return {
      ...toRefs(state),
      onOpen,
      onClose,
      handleConfirm,
    }
  },
}
</script>
